home *** CD-ROM | disk | FTP | other *** search
/ 100 Best Shareware & Freeware Games / 100 Games.iso / Cards / PySol / pysol460.exe / {app} / python / Lib / lib-tk / Tkinter.py < prev    next >
Encoding:
Python Source  |  2001-07-27  |  64.9 KB  |  1,975 lines

  1. # Tkinter.py -- Tk/Tcl widget wrappers
  2.  
  3. __version__ = "$Revision: 1.127 $"
  4.  
  5. import sys
  6. if sys.platform == "win32":
  7.     import FixTk # Attempt to configure Tcl/Tk without requiring PATH
  8. import _tkinter # If this fails your Python may not be configured for Tk
  9. tkinter = _tkinter # b/w compat for export
  10. TclError = _tkinter.TclError
  11. from types import *
  12. from Tkconstants import *
  13. import string; _string = string; del string
  14. try:
  15.     import MacOS; _MacOS = MacOS; del MacOS
  16. except ImportError:
  17.     _MacOS = None
  18.  
  19. TkVersion = _string.atof(_tkinter.TK_VERSION)
  20. TclVersion = _string.atof(_tkinter.TCL_VERSION)
  21.  
  22. READABLE = _tkinter.READABLE
  23. WRITABLE = _tkinter.WRITABLE
  24. EXCEPTION = _tkinter.EXCEPTION
  25.  
  26. # These are not always defined, e.g. not on Win32 with Tk 8.0 :-(
  27. try: _tkinter.createfilehandler
  28. except AttributeError: _tkinter.createfilehandler = None
  29. try: _tkinter.deletefilehandler
  30. except AttributeError: _tkinter.deletefilehandler = None
  31.     
  32.     
  33. def _flatten(tuple):
  34.     res = ()
  35.     for item in tuple:
  36.         if type(item) in (TupleType, ListType):
  37.             res = res + _flatten(item)
  38.         elif item is not None:
  39.             res = res + (item,)
  40.     return res
  41.  
  42. try: _flatten = _tkinter._flatten
  43. except AttributeError: pass
  44.  
  45. def _cnfmerge(cnfs):
  46.     if type(cnfs) is DictionaryType:
  47.         return cnfs
  48.     elif type(cnfs) in (NoneType, StringType):
  49.         return cnfs
  50.     else:
  51.         cnf = {}
  52.         for c in _flatten(cnfs):
  53.             try:
  54.                 cnf.update(c)
  55.             except (AttributeError, TypeError), msg:
  56.                 print "_cnfmerge: fallback due to:", msg
  57.                 for k, v in c.items():
  58.                     cnf[k] = v
  59.         return cnf
  60.  
  61. try: _cnfmerge = _tkinter._cnfmerge
  62. except AttributeError: pass
  63.  
  64. class Event:
  65.     pass
  66.  
  67. _support_default_root = 1
  68. _default_root = None
  69.  
  70. def NoDefaultRoot():
  71.     global _support_default_root
  72.     _support_default_root = 0
  73.     global _default_root
  74.     _default_root = None
  75.     del _default_root
  76.  
  77. def _tkerror(err):
  78.     pass
  79.  
  80. def _exit(code='0'):
  81.     raise SystemExit, code
  82.  
  83. _varnum = 0
  84. class Variable:
  85.     _default = ""
  86.     def __init__(self, master=None):
  87.         global _varnum
  88.         if not master:
  89.             master = _default_root
  90.         self._master = master
  91.         self._tk = master.tk
  92.         self._name = 'PY_VAR' + `_varnum`
  93.         _varnum = _varnum + 1
  94.         self.set(self._default)
  95.     def __del__(self):
  96.         self._tk.globalunsetvar(self._name)
  97.     def __str__(self):
  98.         return self._name
  99.     def set(self, value):
  100.         return self._tk.globalsetvar(self._name, value)
  101.     def trace_variable(self, mode, callback):
  102.         cbname = self._master._register(callback)
  103.         self._tk.call("trace", "variable", self._name, mode, cbname)
  104.         return cbname
  105.     trace = trace_variable
  106.     def trace_vdelete(self, mode, cbname):
  107.         self._tk.call("trace", "vdelete", self._name, mode, cbname)
  108.         self._master.deletecommand(cbname)
  109.     def trace_vinfo(self):
  110.         return map(self._tk.split, self._tk.splitlist(
  111.             self._tk.call("trace", "vinfo", self._name)))
  112.  
  113. class StringVar(Variable):
  114.     _default = ""
  115.     def __init__(self, master=None):
  116.         Variable.__init__(self, master)
  117.     def get(self):
  118.         return self._tk.globalgetvar(self._name)
  119.  
  120. class IntVar(Variable):
  121.     _default = 0
  122.     def __init__(self, master=None):
  123.         Variable.__init__(self, master)
  124.     def get(self):
  125.         return getint(self._tk.globalgetvar(self._name))
  126.  
  127. class DoubleVar(Variable):
  128.     _default = 0.0
  129.     def __init__(self, master=None):
  130.         Variable.__init__(self, master)
  131.     def get(self):
  132.         return getdouble(self._tk.globalgetvar(self._name))
  133.  
  134. class BooleanVar(Variable):
  135.     _default = "false"
  136.     def __init__(self, master=None):
  137.         Variable.__init__(self, master)
  138.     def get(self):
  139.         return self._tk.getboolean(self._tk.globalgetvar(self._name))
  140.  
  141. def mainloop(n=0):
  142.     _default_root.tk.mainloop(n)
  143.  
  144. getint = int
  145.  
  146. getdouble = float
  147.  
  148. def getboolean(s):
  149.     return _default_root.tk.getboolean(s)
  150.  
  151. # Methods defined on both toplevel and interior widgets
  152. class Misc:
  153.     # XXX font command?
  154.     _tclCommands = None
  155.     def destroy(self):
  156.         if self._tclCommands is not None:
  157.             for name in self._tclCommands:
  158.                 #print '- Tkinter: deleted command', name
  159.                 try:
  160.                     self.tk.deletecommand(name)
  161.                 except:
  162.                     pass
  163.             self._tclCommands = None
  164.     def deletecommand(self, name):
  165.         #print '- Tkinter: deleted command', name
  166.         self.tk.deletecommand(name)
  167.         try:
  168.             self._tclCommands.remove(name)
  169.         except ValueError:
  170.             pass
  171.     def tk_strictMotif(self, boolean=None):
  172.         return self.tk.getboolean(self.tk.call(
  173.             'set', 'tk_strictMotif', boolean))
  174.     def tk_bisque(self):
  175.         self.tk.call('tk_bisque')
  176.     def tk_setPalette(self, *args, **kw):
  177.         self.tk.call(('tk_setPalette',)
  178.               + _flatten(args) + _flatten(kw.items()))
  179.     def tk_menuBar(self, *args):
  180.         pass # obsolete since Tk 4.0
  181.     def wait_variable(self, name='PY_VAR'):
  182.         self.tk.call('tkwait', 'variable', name)
  183.     waitvar = wait_variable # XXX b/w compat
  184.     def wait_window(self, window=None):
  185.         if window == None:
  186.             window = self
  187.         self.tk.call('tkwait', 'window', window._w)
  188.     def wait_visibility(self, window=None):
  189.         if window == None:
  190.             window = self
  191.         self.tk.call('tkwait', 'visibility', window._w)
  192.     def setvar(self, name='PY_VAR', value='1'):
  193.         self.tk.setvar(name, value)
  194.     def getvar(self, name='PY_VAR'):
  195.         return self.tk.getvar(name)
  196.     getint = int
  197.     getdouble = float
  198.     def getboolean(self, s):
  199.         return self.tk.getboolean(s)
  200.     def focus_set(self):
  201.         self.tk.call('focus', self._w)
  202.     focus = focus_set # XXX b/w compat?
  203.     def focus_force(self):
  204.         self.tk.call('focus', '-force', self._w)
  205.     def focus_get(self):
  206.         name = self.tk.call('focus')
  207.         if name == 'none' or not name: return None
  208.         return self._nametowidget(name)
  209.     def focus_displayof(self):
  210.         name = self.tk.call('focus', '-displayof', self._w)
  211.         if name == 'none' or not name: return None
  212.         return self._nametowidget(name)
  213.     def focus_lastfor(self):
  214.         name = self.tk.call('focus', '-lastfor', self._w)
  215.         if name == 'none' or not name: return None
  216.         return self._nametowidget(name)
  217.     def tk_focusFollowsMouse(self):
  218.         self.tk.call('tk_focusFollowsMouse')
  219.     def tk_focusNext(self):
  220.         name = self.tk.call('tk_focusNext', self._w)
  221.         if not name: return None
  222.         return self._nametowidget(name)
  223.     def tk_focusPrev(self):
  224.         name = self.tk.call('tk_focusPrev', self._w)
  225.         if not name: return None
  226.         return self._nametowidget(name)
  227.     def after(self, ms, func=None, *args):
  228.         if not func:
  229.             # I'd rather use time.sleep(ms*0.001)
  230.             self.tk.call('after', ms)
  231.         else:
  232.             # XXX Disgusting hack to clean up after calling func
  233.             tmp = []
  234.             def callit(func=func, args=args, self=self, tmp=tmp):
  235.                 try:
  236.                     apply(func, args)
  237.                 finally:
  238.                     try:
  239.                         self.deletecommand(tmp[0])
  240.                     except TclError:
  241.                         pass
  242.             name = self._register(callit)
  243.             tmp.append(name)
  244.             return self.tk.call('after', ms, name)
  245.     def after_idle(self, func, *args):
  246.         return apply(self.after, ('idle', func) + args)
  247.     def after_cancel(self, id):
  248.         self.tk.call('after', 'cancel', id)
  249.     def bell(self, displayof=0):
  250.         self.tk.call(('bell',) + self._displayof(displayof))
  251.     # Clipboard handling:
  252.     def clipboard_clear(self, **kw):
  253.         if not kw.has_key('displayof'): kw['displayof'] = self._w
  254.         self.tk.call(('clipboard', 'clear') + self._options(kw))
  255.     def clipboard_append(self, string, **kw):
  256.         if not kw.has_key('displayof'): kw['displayof'] = self._w
  257.         self.tk.call(('clipboard', 'append') + self._options(kw)
  258.               + ('--', string))
  259.     # XXX grab current w/o window argument
  260.     def grab_current(self):
  261.         name = self.tk.call('grab', 'current', self._w)
  262.         if not name: return None
  263.         return self._nametowidget(name)
  264.     def grab_release(self):
  265.         self.tk.call('grab', 'release', self._w)
  266.     def grab_set(self):
  267.         self.tk.call('grab', 'set', self._w)
  268.     def grab_set_global(self):
  269.         self.tk.call('grab', 'set', '-global', self._w)
  270.     def grab_status(self):
  271.         status = self.tk.call('grab', 'status', self._w)
  272.         if status == 'none': status = None
  273.         return status
  274.     def lower(self, belowThis=None):
  275.         self.tk.call('lower', self._w, belowThis)
  276.     def option_add(self, pattern, value, priority = None):
  277.         self.tk.call('option', 'add', pattern, value, priority)
  278.     def option_clear(self):
  279.         self.tk.call('option', 'clear')
  280.     def option_get(self, name, className):
  281.         return self.tk.call('option', 'get', self._w, name, className)
  282.     def option_readfile(self, fileName, priority = None):
  283.         self.tk.call('option', 'readfile', fileName, priority)
  284.     def selection_clear(self, **kw):
  285.         if not kw.has_key('displayof'): kw['displayof'] = self._w
  286.         self.tk.call(('selection', 'clear') + self._options(kw))
  287.     def selection_get(self, **kw):
  288.         if not kw.has_key('displayof'): kw['displayof'] = self._w
  289.         return self.tk.call(('selection', 'get') + self._options(kw))
  290.     def selection_handle(self, command, **kw):
  291.         name = self._register(command)
  292.         self.tk.call(('selection', 'handle') + self._options(kw)
  293.               + (self._w, name))
  294.     def selection_own(self, **kw):
  295.         "Become owner of X selection."
  296.         self.tk.call(('selection', 'own') +
  297.                  self._options(kw) + (self._w,))
  298.     def selection_own_get(self, **kw):
  299.         "Find owner of X selection."
  300.         if not kw.has_key('displayof'): kw['displayof'] = self._w
  301.         name = self.tk.call(('selection', 'own') + self._options(kw))
  302.         if not name: return None
  303.         return self._nametowidget(name)
  304.     def send(self, interp, cmd, *args):
  305.         return self.tk.call(('send', interp, cmd) + args)
  306.     def lower(self, belowThis=None):
  307.         self.tk.call('lower', self._w, belowThis)
  308.     def tkraise(self, aboveThis=None):
  309.         self.tk.call('raise', self._w, aboveThis)
  310.     lift = tkraise
  311.     def colormodel(self, value=None):
  312.         return self.tk.call('tk', 'colormodel', self._w, value)
  313.     def winfo_atom(self, name, displayof=0):
  314.         args = ('winfo', 'atom') + self._displayof(displayof) + (name,)
  315.         return getint(self.tk.call(args))
  316.     def winfo_atomname(self, id, displayof=0):
  317.         args = ('winfo', 'atomname') \
  318.                + self._displayof(displayof) + (id,)
  319.         return self.tk.call(args)
  320.     def winfo_cells(self):
  321.         return getint(
  322.             self.tk.call('winfo', 'cells', self._w))
  323.     def winfo_children(self):
  324.         return map(self._nametowidget,
  325.                self.tk.splitlist(self.tk.call(
  326.                    'winfo', 'children', self._w)))
  327.     def winfo_class(self):
  328.         return self.tk.call('winfo', 'class', self._w)
  329.     def winfo_colormapfull(self):
  330.         return self.tk.getboolean(
  331.             self.tk.call('winfo', 'colormapfull', self._w))
  332.     def winfo_containing(self, rootX, rootY, displayof=0):
  333.         args = ('winfo', 'containing') \
  334.                + self._displayof(displayof) + (rootX, rootY)
  335.         name = self.tk.call(args)
  336.         if not name: return None
  337.         return self._nametowidget(name)
  338.     def winfo_depth(self):
  339.         return getint(self.tk.call('winfo', 'depth', self._w))
  340.     def winfo_exists(self):
  341.         return getint(
  342.             self.tk.call('winfo', 'exists', self._w))
  343.     def winfo_fpixels(self, number):
  344.         return getdouble(self.tk.call(
  345.             'winfo', 'fpixels', self._w, number))
  346.     def winfo_geometry(self):
  347.         return self.tk.call('winfo', 'geometry', self._w)
  348.     def winfo_height(self):
  349.         return getint(
  350.             self.tk.call('winfo', 'height', self._w))
  351.     def winfo_id(self):
  352.         return self.tk.getint(
  353.             self.tk.call('winfo', 'id', self._w))
  354.     def winfo_interps(self, displayof=0):
  355.         args = ('winfo', 'interps') + self._displayof(displayof)
  356.         return self.tk.splitlist(self.tk.call(args))
  357.     def winfo_ismapped(self):
  358.         return getint(
  359.             self.tk.call('winfo', 'ismapped', self._w))
  360.     def winfo_manager(self):
  361.         return self.tk.call('winfo', 'manager', self._w)
  362.     def winfo_name(self):
  363.         return self.tk.call('winfo', 'name', self._w)
  364.     def winfo_parent(self):
  365.         return self.tk.call('winfo', 'parent', self._w)
  366.     def winfo_pathname(self, id, displayof=0):
  367.         args = ('winfo', 'pathname') \
  368.                + self._displayof(displayof) + (id,)
  369.         return self.tk.call(args)
  370.     def winfo_pixels(self, number):
  371.         return getint(
  372.             self.tk.call('winfo', 'pixels', self._w, number))
  373.     def winfo_pointerx(self):
  374.         return getint(
  375.             self.tk.call('winfo', 'pointerx', self._w))
  376.     def winfo_pointerxy(self):
  377.         return self._getints(
  378.             self.tk.call('winfo', 'pointerxy', self._w))
  379.     def winfo_pointery(self):
  380.         return getint(
  381.             self.tk.call('winfo', 'pointery', self._w))
  382.     def winfo_reqheight(self):
  383.         return getint(
  384.             self.tk.call('winfo', 'reqheight', self._w))
  385.     def winfo_reqwidth(self):
  386.         return getint(
  387.             self.tk.call('winfo', 'reqwidth', self._w))
  388.     def winfo_rgb(self, color):
  389.         return self._getints(
  390.             self.tk.call('winfo', 'rgb', self._w, color))
  391.     def winfo_rootx(self):
  392.         return getint(
  393.             self.tk.call('winfo', 'rootx', self._w))
  394.     def winfo_rooty(self):
  395.         return getint(
  396.             self.tk.call('winfo', 'rooty', self._w))
  397.     def winfo_screen(self):
  398.         return self.tk.call('winfo', 'screen', self._w)
  399.     def winfo_screencells(self):
  400.         return getint(
  401.             self.tk.call('winfo', 'screencells', self._w))
  402.     def winfo_screendepth(self):
  403.         return getint(
  404.             self.tk.call('winfo', 'screendepth', self._w))
  405.     def winfo_screenheight(self):
  406.         return getint(
  407.             self.tk.call('winfo', 'screenheight', self._w))
  408.     def winfo_screenmmheight(self):
  409.         return getint(
  410.             self.tk.call('winfo', 'screenmmheight', self._w))
  411.     def winfo_screenmmwidth(self):
  412.         return getint(
  413.             self.tk.call('winfo', 'screenmmwidth', self._w))
  414.     def winfo_screenvisual(self):
  415.         return self.tk.call('winfo', 'screenvisual', self._w)
  416.     def winfo_screenwidth(self):
  417.         return getint(
  418.             self.tk.call('winfo', 'screenwidth', self._w))
  419.     def winfo_server(self):
  420.         return self.tk.call('winfo', 'server', self._w)
  421.     def winfo_toplevel(self):
  422.         return self._nametowidget(self.tk.call(
  423.             'winfo', 'toplevel', self._w))
  424.     def winfo_viewable(self):
  425.         return getint(
  426.             self.tk.call('winfo', 'viewable', self._w))
  427.     def winfo_visual(self):
  428.         return self.tk.call('winfo', 'visual', self._w)
  429.     def winfo_visualid(self):
  430.         return self.tk.call('winfo', 'visualid', self._w)
  431.     def winfo_visualsavailable(self, includeids=0):
  432.         data = self.tk.split(
  433.             self.tk.call('winfo', 'visualsavailable', self._w,
  434.                      includeids and 'includeids' or None))
  435.         def parseitem(x, self=self):
  436.             return x[:1] + tuple(map(getint, x[1:]))
  437.         return map(parseitem, data)
  438.     def winfo_vrootheight(self):
  439.         return getint(
  440.             self.tk.call('winfo', 'vrootheight', self._w))
  441.     def winfo_vrootwidth(self):
  442.         return getint(
  443.             self.tk.call('winfo', 'vrootwidth', self._w))
  444.     def winfo_vrootx(self):
  445.         return getint(
  446.             self.tk.call('winfo', 'vrootx', self._w))
  447.     def winfo_vrooty(self):
  448.         return getint(
  449.             self.tk.call('winfo', 'vrooty', self._w))
  450.     def winfo_width(self):
  451.         return getint(
  452.             self.tk.call('winfo', 'width', self._w))
  453.     def winfo_x(self):
  454.         return getint(
  455.             self.tk.call('winfo', 'x', self._w))
  456.     def winfo_y(self):
  457.         return getint(
  458.             self.tk.call('winfo', 'y', self._w))
  459.     def update(self):
  460.         self.tk.call('update')
  461.     def update_idletasks(self):
  462.         self.tk.call('update', 'idletasks')
  463.     def bindtags(self, tagList=None):
  464.         if tagList is None:
  465.             return self.tk.splitlist(
  466.                 self.tk.call('bindtags', self._w))
  467.         else:
  468.             self.tk.call('bindtags', self._w, tagList)
  469.     def _bind(self, what, sequence, func, add, needcleanup=1):
  470.         if type(func) is StringType:
  471.             self.tk.call(what + (sequence, func))
  472.         elif func:
  473.             funcid = self._register(func, self._substitute,
  474.                         needcleanup)
  475.             cmd = ('%sif {"[%s %s]" == "break"} break\n'
  476.                    %
  477.                    (add and '+' or '',
  478.                 funcid,
  479.                 _string.join(self._subst_format)))
  480.             self.tk.call(what + (sequence, cmd))
  481.             return funcid
  482.         elif sequence:
  483.             return self.tk.call(what + (sequence,))
  484.         else:
  485.             return self.tk.splitlist(self.tk.call(what))
  486.     def bind(self, sequence=None, func=None, add=None):
  487.         return self._bind(('bind', self._w), sequence, func, add)
  488.     def unbind(self, sequence, funcid=None):
  489.         self.tk.call('bind', self._w, sequence, '')
  490.         if funcid:
  491.             self.deletecommand(funcid)
  492.     def bind_all(self, sequence=None, func=None, add=None):
  493.         return self._bind(('bind', 'all'), sequence, func, add, 0)
  494.     def unbind_all(self, sequence):
  495.         self.tk.call('bind', 'all' , sequence, '')
  496.     def bind_class(self, className, sequence=None, func=None, add=None):
  497.         return self._bind(('bind', className), sequence, func, add, 0)
  498.     def unbind_class(self, className, sequence):
  499.         self.tk.call('bind', className , sequence, '')
  500.     def mainloop(self, n=0):
  501.         self.tk.mainloop(n)
  502.     def quit(self):
  503.         self.tk.quit()
  504.     def _getints(self, string):
  505.         if string:
  506.             return tuple(map(getint, self.tk.splitlist(string)))
  507.     def _getdoubles(self, string):
  508.         if string:
  509.             return tuple(map(getdouble, self.tk.splitlist(string)))
  510.     def _getboolean(self, string):
  511.         if string:
  512.             return self.tk.getboolean(string)
  513.     def _displayof(self, displayof):
  514.         if displayof:
  515.             return ('-displayof', displayof)
  516.         if displayof is None:
  517.             return ('-displayof', self._w)
  518.         return ()
  519.     def _options(self, cnf, kw = None):
  520.         if kw:
  521.             cnf = _cnfmerge((cnf, kw))
  522.         else:
  523.             cnf = _cnfmerge(cnf)
  524.         res = ()
  525.         for k, v in cnf.items():
  526.             if v is not None:
  527.                 if k[-1] == '_': k = k[:-1]
  528.                 if callable(v):
  529.                     v = self._register(v)
  530.                 res = res + ('-'+k, v)
  531.         return res
  532.     def nametowidget(self, name):
  533.         w = self
  534.         if name[0] == '.':
  535.             w = w._root()
  536.             name = name[1:]
  537.         find = _string.find
  538.         while name:
  539.             i = find(name, '.')
  540.             if i >= 0:
  541.                 name, tail = name[:i], name[i+1:]
  542.             else:
  543.                 tail = ''
  544.             w = w.children[name]
  545.             name = tail
  546.         return w
  547.     _nametowidget = nametowidget
  548.     def _register(self, func, subst=None, needcleanup=1):
  549.         f = CallWrapper(func, subst, self).__call__
  550.         name = `id(f)`
  551.         try:
  552.             func = func.im_func
  553.         except AttributeError:
  554.             pass
  555.         try:
  556.             name = name + func.__name__
  557.         except AttributeError:
  558.             pass
  559.         self.tk.createcommand(name, f)
  560.         if needcleanup:
  561.             if self._tclCommands is None:
  562.                 self._tclCommands = []
  563.             self._tclCommands.append(name)
  564.         #print '+ Tkinter created command', name
  565.         return name
  566.     register = _register
  567.     def _root(self):
  568.         w = self
  569.         while w.master: w = w.master
  570.         return w
  571.     _subst_format = ('%#', '%b', '%f', '%h', '%k', 
  572.              '%s', '%t', '%w', '%x', '%y',
  573.              '%A', '%E', '%K', '%N', '%W', '%T', '%X', '%Y')
  574.     def _substitute(self, *args):
  575.         if len(args) != len(self._subst_format): return args
  576.         getboolean = self.tk.getboolean
  577.         getint = int
  578.         nsign, b, f, h, k, s, t, w, x, y, A, E, K, N, W, T, X, Y = args
  579.         # Missing: (a, c, d, m, o, v, B, R)
  580.         e = Event()
  581.         e.serial = getint(nsign)
  582.         e.num = getint(b)
  583.         try: e.focus = getboolean(f)
  584.         except TclError: pass
  585.         e.height = getint(h)
  586.         e.keycode = getint(k)
  587.         # For Visibility events, event state is a string and
  588.         # not an integer:
  589.         try:
  590.             e.state = getint(s)
  591.         except ValueError:
  592.             e.state = s
  593.         e.time = getint(t)
  594.         e.width = getint(w)
  595.         e.x = getint(x)
  596.         e.y = getint(y)
  597.         e.char = A
  598.         try: e.send_event = getboolean(E)
  599.         except TclError: pass
  600.         e.keysym = K
  601.         e.keysym_num = getint(N)
  602.         e.type = T
  603.         try:
  604.             e.widget = self._nametowidget(W)
  605.         except KeyError:
  606.             e.widget = W
  607.         e.x_root = getint(X)
  608.         e.y_root = getint(Y)
  609.         return (e,)
  610.     def _report_exception(self):
  611.         import sys
  612.         exc, val, tb = sys.exc_type, sys.exc_value, sys.exc_traceback
  613.         root = self._root()
  614.         root.report_callback_exception(exc, val, tb)
  615.     # These used to be defined in Widget:
  616.     def configure(self, cnf=None, **kw):
  617.         # XXX ought to generalize this so tag_config etc. can use it
  618.         if kw:
  619.             cnf = _cnfmerge((cnf, kw))
  620.         elif cnf:
  621.             cnf = _cnfmerge(cnf)
  622.         if cnf is None:
  623.             cnf = {}
  624.             for x in self.tk.split(
  625.                 self.tk.call(self._w, 'configure')):
  626.                 cnf[x[0][1:]] = (x[0][1:],) + x[1:]
  627.             return cnf
  628.         if type(cnf) is StringType:
  629.             x = self.tk.split(self.tk.call(
  630.                 self._w, 'configure', '-'+cnf))
  631.             return (x[0][1:],) + x[1:]
  632.         self.tk.call((self._w, 'configure')
  633.               + self._options(cnf))
  634.     config = configure
  635.     def cget(self, key):
  636.         return self.tk.call(self._w, 'cget', '-' + key)
  637.     __getitem__ = cget
  638.     def __setitem__(self, key, value):
  639.         self.configure({key: value})
  640.     def keys(self):
  641.         return map(lambda x: x[0][1:],
  642.                self.tk.split(self.tk.call(self._w, 'configure')))
  643.     def __str__(self):
  644.         return self._w
  645.     # Pack methods that apply to the master
  646.     _noarg_ = ['_noarg_']
  647.     def pack_propagate(self, flag=_noarg_):
  648.         if flag is Misc._noarg_:
  649.             return self._getboolean(self.tk.call(
  650.                 'pack', 'propagate', self._w))
  651.         else:
  652.             self.tk.call('pack', 'propagate', self._w, flag)
  653.     propagate = pack_propagate
  654.     def pack_slaves(self):
  655.         return map(self._nametowidget,
  656.                self.tk.splitlist(
  657.                    self.tk.call('pack', 'slaves', self._w)))
  658.     slaves = pack_slaves
  659.     # Place method that applies to the master
  660.     def place_slaves(self):
  661.         return map(self._nametowidget,
  662.                self.tk.splitlist(
  663.                    self.tk.call(
  664.                        'place', 'slaves', self._w)))
  665.     # Grid methods that apply to the master
  666.     def grid_bbox(self, column=None, row=None, col2=None, row2=None):
  667.         args = ('grid', 'bbox', self._w)
  668.         if column is not None and row is not None:
  669.             args = args + (column, row)
  670.         if col2 is not None and row2 is not None:
  671.             args = args + (col2, row2)
  672.         return self._getints(apply(self.tk.call, args)) or None
  673.  
  674.     bbox = grid_bbox
  675.     def _grid_configure(self, command, index, cnf, kw):
  676.         if type(cnf) is StringType and not kw:
  677.             if cnf[-1:] == '_':
  678.                 cnf = cnf[:-1]
  679.             if cnf[:1] != '-':
  680.                 cnf = '-'+cnf
  681.             options = (cnf,)
  682.         else:
  683.             options = self._options(cnf, kw)
  684.         if not options:
  685.             res = self.tk.call('grid',
  686.                        command, self._w, index)
  687.             words = self.tk.splitlist(res)
  688.             dict = {}
  689.             for i in range(0, len(words), 2):
  690.                 key = words[i][1:]
  691.                 value = words[i+1]
  692.                 if not value:
  693.                     value = None
  694.                 elif '.' in value:
  695.                     value = getdouble(value)
  696.                 else:
  697.                     value = getint(value)
  698.                 dict[key] = value
  699.             return dict
  700.         res = self.tk.call(
  701.                   ('grid', command, self._w, index) 
  702.                   + options)
  703.         if len(options) == 1:
  704.             if not res: return None
  705.             # In Tk 7.5, -width can be a float
  706.             if '.' in res: return getdouble(res)
  707.             return getint(res)
  708.     def grid_columnconfigure(self, index, cnf={}, **kw):
  709.         return self._grid_configure('columnconfigure', index, cnf, kw)
  710.     columnconfigure = grid_columnconfigure
  711.     def grid_propagate(self, flag=_noarg_):
  712.         if flag is Misc._noarg_:
  713.             return self._getboolean(self.tk.call(
  714.                 'grid', 'propagate', self._w))
  715.         else:
  716.             self.tk.call('grid', 'propagate', self._w, flag)
  717.     def grid_rowconfigure(self, index, cnf={}, **kw):
  718.         return self._grid_configure('rowconfigure', index, cnf, kw)
  719.     rowconfigure = grid_rowconfigure
  720.     def grid_size(self):
  721.         return self._getints(
  722.             self.tk.call('grid', 'size', self._w)) or None
  723.     size = grid_size
  724.     def grid_slaves(self, row=None, column=None):
  725.         args = ()
  726.         if row is not None:
  727.             args = args + ('-row', row)
  728.         if column is not None:
  729.             args = args + ('-column', column)
  730.         return map(self._nametowidget,
  731.                self.tk.splitlist(self.tk.call(
  732.                    ('grid', 'slaves', self._w) + args)))
  733.  
  734.     # Support for the "event" command, new in Tk 4.2.
  735.     # By Case Roole.
  736.  
  737.     def event_add(self, virtual, *sequences):
  738.         args = ('event', 'add', virtual) + sequences
  739.         self.tk.call(args)
  740.  
  741.     def event_delete(self, virtual, *sequences):
  742.         args = ('event', 'delete', virtual) + sequences
  743.         self.tk.call(args)
  744.  
  745.     def event_generate(self, sequence, **kw):
  746.         args = ('event', 'generate', self._w, sequence)
  747.         for k, v in kw.items():
  748.             args = args + ('-%s' % k, str(v))
  749.         self.tk.call(args)
  750.  
  751.     def event_info(self, virtual=None):
  752.         return self.tk.splitlist(
  753.             self.tk.call('event', 'info', virtual))
  754.  
  755.     # Image related commands
  756.  
  757.     def image_names(self):
  758.         return self.tk.call('image', 'names')
  759.  
  760.     def image_types(self):
  761.         return self.tk.call('image', 'types')
  762.  
  763.  
  764. class CallWrapper:
  765.     def __init__(self, func, subst, widget):
  766.         self.func = func
  767.         self.subst = subst
  768.         self.widget = widget
  769.     def __call__(self, *args):
  770.         try:
  771.             if self.subst:
  772.                 args = apply(self.subst, args)
  773.             return apply(self.func, args)
  774.         except SystemExit, msg:
  775.             raise SystemExit, msg
  776.         except:
  777.             self.widget._report_exception()
  778.  
  779.  
  780. class Wm:
  781.     def wm_aspect(self, 
  782.            minNumer=None, minDenom=None, 
  783.            maxNumer=None, maxDenom=None):
  784.         return self._getints(
  785.             self.tk.call('wm', 'aspect', self._w, 
  786.                      minNumer, minDenom, 
  787.                      maxNumer, maxDenom))
  788.     aspect = wm_aspect
  789.     def wm_client(self, name=None):
  790.         return self.tk.call('wm', 'client', self._w, name)
  791.     client = wm_client
  792.     def wm_colormapwindows(self, *wlist):
  793.         args = ('wm', 'colormapwindows', self._w) + _flatten(wlist)
  794.         return map(self._nametowidget, self.tk.call(args))
  795.     colormapwindows = wm_colormapwindows
  796.     def wm_command(self, value=None):
  797.         return self.tk.call('wm', 'command', self._w, value)
  798.     command = wm_command
  799.     def wm_deiconify(self):
  800.         return self.tk.call('wm', 'deiconify', self._w)
  801.     deiconify = wm_deiconify
  802.     def wm_focusmodel(self, model=None):
  803.         return self.tk.call('wm', 'focusmodel', self._w, model)
  804.     focusmodel = wm_focusmodel
  805.     def wm_frame(self):
  806.         return self.tk.call('wm', 'frame', self._w)
  807.     frame = wm_frame
  808.     def wm_geometry(self, newGeometry=None):
  809.         return self.tk.call('wm', 'geometry', self._w, newGeometry)
  810.     geometry = wm_geometry
  811.     def wm_grid(self,
  812.          baseWidth=None, baseHeight=None, 
  813.          widthInc=None, heightInc=None):
  814.         return self._getints(self.tk.call(
  815.             'wm', 'grid', self._w,
  816.             baseWidth, baseHeight, widthInc, heightInc))
  817.     grid = wm_grid
  818.     def wm_group(self, pathName=None):
  819.         return self.tk.call('wm', 'group', self._w, pathName)
  820.     group = wm_group
  821.     def wm_iconbitmap(self, bitmap=None):
  822.         return self.tk.call('wm', 'iconbitmap', self._w, bitmap)
  823.     iconbitmap = wm_iconbitmap
  824.     def wm_iconify(self):
  825.         return self.tk.call('wm', 'iconify', self._w)
  826.     iconify = wm_iconify
  827.     def wm_iconmask(self, bitmap=None):
  828.         return self.tk.call('wm', 'iconmask', self._w, bitmap)
  829.     iconmask = wm_iconmask
  830.     def wm_iconname(self, newName=None):
  831.         return self.tk.call('wm', 'iconname', self._w, newName)
  832.     iconname = wm_iconname
  833.     def wm_iconposition(self, x=None, y=None):
  834.         return self._getints(self.tk.call(
  835.             'wm', 'iconposition', self._w, x, y))
  836.     iconposition = wm_iconposition
  837.     def wm_iconwindow(self, pathName=None):
  838.         return self.tk.call('wm', 'iconwindow', self._w, pathName)
  839.     iconwindow = wm_iconwindow
  840.     def wm_maxsize(self, width=None, height=None):
  841.         return self._getints(self.tk.call(
  842.             'wm', 'maxsize', self._w, width, height))
  843.     maxsize = wm_maxsize
  844.     def wm_minsize(self, width=None, height=None):
  845.         return self._getints(self.tk.call(
  846.             'wm', 'minsize', self._w, width, height))
  847.     minsize = wm_minsize
  848.     def wm_overrideredirect(self, boolean=None):
  849.         return self._getboolean(self.tk.call(
  850.             'wm', 'overrideredirect', self._w, boolean))
  851.     overrideredirect = wm_overrideredirect
  852.     def wm_positionfrom(self, who=None):
  853.         return self.tk.call('wm', 'positionfrom', self._w, who)
  854.     positionfrom = wm_positionfrom
  855.     def wm_protocol(self, name=None, func=None):
  856.         if callable(func):
  857.             command = self._register(func)
  858.         else:
  859.             command = func
  860.         return self.tk.call(
  861.             'wm', 'protocol', self._w, name, command)
  862.     protocol = wm_protocol
  863.     def wm_resizable(self, width=None, height=None):
  864.         return self.tk.call('wm', 'resizable', self._w, width, height)
  865.     resizable = wm_resizable
  866.     def wm_sizefrom(self, who=None):
  867.         return self.tk.call('wm', 'sizefrom', self._w, who)
  868.     sizefrom = wm_sizefrom
  869.     def wm_state(self):
  870.         return self.tk.call('wm', 'state', self._w)
  871.     state = wm_state
  872.     def wm_title(self, string=None):
  873.         return self.tk.call('wm', 'title', self._w, string)
  874.     title = wm_title
  875.     def wm_transient(self, master=None):
  876.         return self.tk.call('wm', 'transient', self._w, master)
  877.     transient = wm_transient
  878.     def wm_withdraw(self):
  879.         return self.tk.call('wm', 'withdraw', self._w)
  880.     withdraw = wm_withdraw
  881.  
  882.  
  883. class Tk(Misc, Wm):
  884.     _w = '.'
  885.     def __init__(self, screenName=None, baseName=None, className='Tk'):
  886.         global _default_root
  887.         self.master = None
  888.         self.children = {}
  889.         if baseName is None:
  890.             import sys, os
  891.             baseName = os.path.basename(sys.argv[0])
  892.             baseName, ext = os.path.splitext(baseName)
  893.             if ext not in ('.py', '.pyc', '.pyo'):
  894.                 baseName = baseName + ext
  895.         self.tk = _tkinter.create(screenName, baseName, className)
  896.         if _MacOS:
  897.             # Disable event scanning except for Command-Period
  898.             _MacOS.SchedParams(1, 0)
  899.             # Work around nasty MacTk bug
  900.             # XXX Is this one still needed?
  901.             self.update()
  902.         # Version sanity checks
  903.         tk_version = self.tk.getvar('tk_version')
  904.         if tk_version != _tkinter.TK_VERSION:
  905.             raise RuntimeError, \
  906.             "tk.h version (%s) doesn't match libtk.a version (%s)" \
  907.             % (_tkinter.TK_VERSION, tk_version)
  908.         tcl_version = self.tk.getvar('tcl_version')
  909.         if tcl_version != _tkinter.TCL_VERSION:
  910.             raise RuntimeError, \
  911.             "tcl.h version (%s) doesn't match libtcl.a version (%s)" \
  912.             % (_tkinter.TCL_VERSION, tcl_version)
  913.         if TkVersion < 4.0:
  914.             raise RuntimeError, \
  915.             "Tk 4.0 or higher is required; found Tk %s" \
  916.             % str(TkVersion)
  917.         self.tk.createcommand('tkerror', _tkerror)
  918.         self.tk.createcommand('exit', _exit)
  919.         self.readprofile(baseName, className)
  920.         if _support_default_root and not _default_root:
  921.             _default_root = self
  922.     def destroy(self):
  923.         for c in self.children.values(): c.destroy()
  924.         self.tk.call('destroy', self._w)
  925.         Misc.destroy(self)
  926.         global _default_root
  927.         if _support_default_root and _default_root is self:
  928.             _default_root = None
  929.     def readprofile(self, baseName, className):
  930.         import os
  931.         if os.environ.has_key('HOME'): home = os.environ['HOME']
  932.         else: home = os.curdir
  933.         class_tcl = os.path.join(home, '.%s.tcl' % className)
  934.         class_py = os.path.join(home, '.%s.py' % className)
  935.         base_tcl = os.path.join(home, '.%s.tcl' % baseName)
  936.         base_py = os.path.join(home, '.%s.py' % baseName)
  937.         dir = {'self': self}
  938.         exec 'from Tkinter import *' in dir
  939.         if os.path.isfile(class_tcl):
  940.             print 'source', `class_tcl`
  941.             self.tk.call('source', class_tcl)
  942.         if os.path.isfile(class_py):
  943.             print 'execfile', `class_py`
  944.             execfile(class_py, dir)
  945.         if os.path.isfile(base_tcl):
  946.             print 'source', `base_tcl`
  947.             self.tk.call('source', base_tcl)
  948.         if os.path.isfile(base_py):
  949.             print 'execfile', `base_py`
  950.             execfile(base_py, dir)
  951.     def report_callback_exception(self, exc, val, tb):
  952.         import traceback, sys
  953.         sys.stderr.write("Exception in Tkinter callback\n")
  954.         sys.last_type = exc
  955.         sys.last_value = val
  956.         sys.last_traceback = tb
  957.         traceback.print_exception(exc, val, tb)
  958.  
  959. # Ideally, the classes Pack, Place and Grid disappear, the
  960. # pack/place/grid methods are defined on the Widget class, and
  961. # everybody uses w.pack_whatever(...) instead of Pack.whatever(w,
  962. # ...), with pack(), place() and grid() being short for
  963. # pack_configure(), place_configure() and grid_columnconfigure(), and
  964. # forget() being short for pack_forget().  As a practical matter, I'm
  965. # afraid that there is too much code out there that may be using the
  966. # Pack, Place or Grid class, so I leave them intact -- but only as
  967. # backwards compatibility features.  Also note that those methods that
  968. # take a master as argument (e.g. pack_propagate) have been moved to
  969. # the Misc class (which now incorporates all methods common between
  970. # toplevel and interior widgets).  Again, for compatibility, these are
  971. # copied into the Pack, Place or Grid class.
  972.  
  973. class Pack:
  974.     def pack_configure(self, cnf={}, **kw):
  975.         self.tk.call(
  976.               ('pack', 'configure', self._w) 
  977.               + self._options(cnf, kw))
  978.     pack = configure = config = pack_configure
  979.     def pack_forget(self):
  980.         self.tk.call('pack', 'forget', self._w)
  981.     forget = pack_forget
  982.     def pack_info(self):
  983.         words = self.tk.splitlist(
  984.             self.tk.call('pack', 'info', self._w))
  985.         dict = {}
  986.         for i in range(0, len(words), 2):
  987.             key = words[i][1:]
  988.             value = words[i+1]
  989.             if value[:1] == '.':
  990.                 value = self._nametowidget(value)
  991.             dict[key] = value
  992.         return dict
  993.     info = pack_info
  994.     propagate = pack_propagate = Misc.pack_propagate
  995.     slaves = pack_slaves = Misc.pack_slaves
  996.  
  997. class Place:
  998.     def place_configure(self, cnf={}, **kw):
  999.         for k in ['in_']:
  1000.             if kw.has_key(k):
  1001.                 kw[k[:-1]] = kw[k]
  1002.                 del kw[k]
  1003.         self.tk.call(
  1004.               ('place', 'configure', self._w) 
  1005.               + self._options(cnf, kw))
  1006.     place = configure = config = place_configure
  1007.     def place_forget(self):
  1008.         self.tk.call('place', 'forget', self._w)
  1009.     forget = place_forget
  1010.     def place_info(self):
  1011.         words = self.tk.splitlist(
  1012.             self.tk.call('place', 'info', self._w))
  1013.         dict = {}
  1014.         for i in range(0, len(words), 2):
  1015.             key = words[i][1:]
  1016.             value = words[i+1]
  1017.             if value[:1] == '.':
  1018.                 value = self._nametowidget(value)
  1019.             dict[key] = value
  1020.         return dict
  1021.     info = place_info
  1022.     slaves = place_slaves = Misc.place_slaves
  1023.  
  1024. class Grid:
  1025.     # Thanks to Masazumi Yoshikawa (yosikawa@isi.edu)
  1026.     def grid_configure(self, cnf={}, **kw):
  1027.         self.tk.call(
  1028.               ('grid', 'configure', self._w) 
  1029.               + self._options(cnf, kw))
  1030.     grid = configure = config = grid_configure
  1031.     bbox = grid_bbox = Misc.grid_bbox
  1032.     columnconfigure = grid_columnconfigure = Misc.grid_columnconfigure
  1033.     def grid_forget(self):
  1034.         self.tk.call('grid', 'forget', self._w)
  1035.     forget = grid_forget
  1036.     def grid_info(self):
  1037.         words = self.tk.splitlist(
  1038.             self.tk.call('grid', 'info', self._w))
  1039.         dict = {}
  1040.         for i in range(0, len(words), 2):
  1041.             key = words[i][1:]
  1042.             value = words[i+1]
  1043.             if value[:1] == '.':
  1044.                 value = self._nametowidget(value)
  1045.             dict[key] = value
  1046.         return dict
  1047.     info = grid_info
  1048.     def grid_location(self, x, y):
  1049.         return self._getints(
  1050.             self.tk.call(
  1051.                 'grid', 'location', self._w, x, y)) or None
  1052.     location = grid_location
  1053.     propagate = grid_propagate = Misc.grid_propagate
  1054.     rowconfigure = grid_rowconfigure = Misc.grid_rowconfigure
  1055.     size = grid_size = Misc.grid_size
  1056.     slaves = grid_slaves = Misc.grid_slaves
  1057.  
  1058. class BaseWidget(Misc):
  1059.     def _setup(self, master, cnf):
  1060.         if _support_default_root:
  1061.             global _default_root
  1062.             if not master:
  1063.                 if not _default_root:
  1064.                     _default_root = Tk()
  1065.                 master = _default_root
  1066.         self.master = master
  1067.         self.tk = master.tk
  1068.         name = None
  1069.         if cnf.has_key('name'):
  1070.             name = cnf['name']
  1071.             del cnf['name']
  1072.         if not name:
  1073.             name = `id(self)`
  1074.         self._name = name
  1075.         if master._w=='.':
  1076.             self._w = '.' + name
  1077.         else:
  1078.             self._w = master._w + '.' + name
  1079.         self.children = {}
  1080.         if self.master.children.has_key(self._name):
  1081.             self.master.children[self._name].destroy()
  1082.         self.master.children[self._name] = self
  1083.     def __init__(self, master, widgetName, cnf={}, kw={}, extra=()):
  1084.         if kw:
  1085.             cnf = _cnfmerge((cnf, kw))
  1086.         self.widgetName = widgetName
  1087.         BaseWidget._setup(self, master, cnf)
  1088.         classes = []
  1089.         for k in cnf.keys():
  1090.             if type(k) is ClassType:
  1091.                 classes.append((k, cnf[k]))
  1092.                 del cnf[k]
  1093.         self.tk.call(
  1094.             (widgetName, self._w) + extra + self._options(cnf))
  1095.         for k, v in classes:
  1096.             k.configure(self, v)
  1097.     def destroy(self):
  1098.         for c in self.children.values(): c.destroy()
  1099.         if self.master.children.has_key(self._name):
  1100.             del self.master.children[self._name]
  1101.         self.tk.call('destroy', self._w)
  1102.         Misc.destroy(self)
  1103.     def _do(self, name, args=()):
  1104.         # XXX Obsolete -- better use self.tk.call directly!
  1105.         return self.tk.call((self._w, name) + args)
  1106.  
  1107. class Widget(BaseWidget, Pack, Place, Grid):
  1108.     pass
  1109.  
  1110. class Toplevel(BaseWidget, Wm):
  1111.     def __init__(self, master=None, cnf={}, **kw):
  1112.         if kw:
  1113.             cnf = _cnfmerge((cnf, kw))
  1114.         extra = ()
  1115.         for wmkey in ['screen', 'class_', 'class', 'visual',
  1116.                   'colormap']:
  1117.             if cnf.has_key(wmkey):
  1118.                 val = cnf[wmkey]
  1119.                 # TBD: a hack needed because some keys
  1120.                 # are not valid as keyword arguments
  1121.                 if wmkey[-1] == '_': opt = '-'+wmkey[:-1]
  1122.                 else: opt = '-'+wmkey
  1123.                 extra = extra + (opt, val)
  1124.                 del cnf[wmkey]
  1125.         BaseWidget.__init__(self, master, 'toplevel', cnf, {}, extra)
  1126.         root = self._root()
  1127.         self.iconname(root.iconname())
  1128.         self.title(root.title())
  1129.  
  1130. class Button(Widget):
  1131.     def __init__(self, master=None, cnf={}, **kw):
  1132.         Widget.__init__(self, master, 'button', cnf, kw)
  1133.     def tkButtonEnter(self, *dummy):
  1134.         self.tk.call('tkButtonEnter', self._w)
  1135.     def tkButtonLeave(self, *dummy):
  1136.         self.tk.call('tkButtonLeave', self._w)
  1137.     def tkButtonDown(self, *dummy):
  1138.         self.tk.call('tkButtonDown', self._w)
  1139.     def tkButtonUp(self, *dummy):
  1140.         self.tk.call('tkButtonUp', self._w)
  1141.     def tkButtonInvoke(self, *dummy):
  1142.         self.tk.call('tkButtonInvoke', self._w)
  1143.     def flash(self):
  1144.         self.tk.call(self._w, 'flash')
  1145.     def invoke(self):
  1146.         return self.tk.call(self._w, 'invoke')
  1147.  
  1148. # Indices:
  1149. # XXX I don't like these -- take them away
  1150. def AtEnd():
  1151.     return 'end'
  1152. def AtInsert(*args):
  1153.     s = 'insert'
  1154.     for a in args:
  1155.         if a: s = s + (' ' + a)
  1156.     return s
  1157. def AtSelFirst():
  1158.     return 'sel.first'
  1159. def AtSelLast():
  1160.     return 'sel.last'
  1161. def At(x, y=None):
  1162.     if y is None:
  1163.         return '@' + `x`        
  1164.     else:
  1165.         return '@' + `x` + ',' + `y`
  1166.  
  1167. class Canvas(Widget):
  1168.     _tagcommands = None
  1169.     def __init__(self, master=None, cnf={}, **kw):
  1170.         Widget.__init__(self, master, 'canvas', cnf, kw)
  1171.     def addtag(self, *args):
  1172.         self.tk.call((self._w, 'addtag') + args)
  1173.     def addtag_above(self, newtag, tagOrId):
  1174.         self.addtag(newtag, 'above', tagOrId)
  1175.     def addtag_all(self, newtag):
  1176.         self.addtag(newtag, 'all')
  1177.     def addtag_below(self, newtag, tagOrId):
  1178.         self.addtag(newtag, 'below', tagOrId)
  1179.     def addtag_closest(self, newtag, x, y, halo=None, start=None):
  1180.         self.addtag(newtag, 'closest', x, y, halo, start)
  1181.     def addtag_enclosed(self, newtag, x1, y1, x2, y2):
  1182.         self.addtag(newtag, 'enclosed', x1, y1, x2, y2)
  1183.     def addtag_overlapping(self, newtag, x1, y1, x2, y2):
  1184.         self.addtag(newtag, 'overlapping', x1, y1, x2, y2)
  1185.     def addtag_withtag(self, newtag, tagOrId):
  1186.         self.addtag(newtag, 'withtag', tagOrId)
  1187.     def bbox(self, *args):
  1188.         return self._getints(
  1189.             self.tk.call((self._w, 'bbox') + args)) or None
  1190.     def tag_unbind(self, tagOrId, sequence, funcid=None):
  1191.         self.tk.call(self._w, 'bind', tagOrId, sequence, '')
  1192.         if funcid:
  1193.             self.deletecommand(funcid)
  1194.     def tag_bind(self, tagOrId, sequence=None, func=None, add=None):
  1195.         res = self._bind((self._w, 'bind', tagOrId),
  1196.                  sequence, func, add)
  1197.         if sequence and func and res:
  1198.             # remember the funcid for later
  1199.             if self._tagcommands is None:
  1200.                 self._tagcommands = {}
  1201.             list = self._tagcommands.get(tagOrId) or []
  1202.             self._tagcommands[tagOrId] = list
  1203.             list.append(res)
  1204.         return res
  1205.     def canvasx(self, screenx, gridspacing=None):
  1206.         return getdouble(self.tk.call(
  1207.             self._w, 'canvasx', screenx, gridspacing))
  1208.     def canvasy(self, screeny, gridspacing=None):
  1209.         return getdouble(self.tk.call(
  1210.             self._w, 'canvasy', screeny, gridspacing))
  1211.     def coords(self, *args):
  1212.         # XXX Should use _flatten on args
  1213.         return map(getdouble,
  1214.                            self.tk.splitlist(
  1215.                    self.tk.call((self._w, 'coords') + args)))
  1216.     def _create(self, itemType, args, kw): # Args: (val, val, ..., cnf={})
  1217.         args = _flatten(args)
  1218.         cnf = args[-1]
  1219.         if type(cnf) in (DictionaryType, TupleType):
  1220.             args = args[:-1]
  1221.         else:
  1222.             cnf = {}
  1223.         return getint(apply(
  1224.             self.tk.call,
  1225.             (self._w, 'create', itemType) 
  1226.             + args + self._options(cnf, kw)))
  1227.     def create_arc(self, *args, **kw):
  1228.         return self._create('arc', args, kw)
  1229.     def create_bitmap(self, *args, **kw):
  1230.         return self._create('bitmap', args, kw)
  1231.     def create_image(self, *args, **kw):
  1232.         return self._create('image', args, kw)
  1233.     def create_line(self, *args, **kw):
  1234.         return self._create('line', args, kw)
  1235.     def create_oval(self, *args, **kw):
  1236.         return self._create('oval', args, kw)
  1237.     def create_polygon(self, *args, **kw):
  1238.         return self._create('polygon', args, kw)
  1239.     def create_rectangle(self, *args, **kw):
  1240.         return self._create('rectangle', args, kw)
  1241.     def create_text(self, *args, **kw):
  1242.         return self._create('text', args, kw)
  1243.     def create_window(self, *args, **kw):
  1244.         return self._create('window', args, kw)
  1245.     def dchars(self, *args):
  1246.         self.tk.call((self._w, 'dchars') + args)
  1247.     def delete(self, *args):
  1248.         self.tk.call((self._w, 'delete') + args)
  1249.     def dtag(self, *args):
  1250.         self.tk.call((self._w, 'dtag') + args)
  1251.     def find(self, *args):
  1252.         return self._getints(
  1253.             self.tk.call((self._w, 'find') + args)) or ()
  1254.     def find_above(self, tagOrId):
  1255.         return self.find('above', tagOrId)
  1256.     def find_all(self):
  1257.         return self.find('all')
  1258.     def find_below(self, tagOrId):
  1259.         return self.find('below', tagOrId)
  1260.     def find_closest(self, x, y, halo=None, start=None):
  1261.         return self.find('closest', x, y, halo, start)
  1262.     def find_enclosed(self, x1, y1, x2, y2):
  1263.         return self.find('enclosed', x1, y1, x2, y2)
  1264.     def find_overlapping(self, x1, y1, x2, y2):
  1265.         return self.find('overlapping', x1, y1, x2, y2)
  1266.     def find_withtag(self, tagOrId):
  1267.         return self.find('withtag', tagOrId)
  1268.     def focus(self, *args):
  1269.         return self.tk.call((self._w, 'focus') + args)
  1270.     def gettags(self, *args):
  1271.         return self.tk.splitlist(
  1272.             self.tk.call((self._w, 'gettags') + args))
  1273.     def icursor(self, *args):
  1274.         self.tk.call((self._w, 'icursor') + args)
  1275.     def index(self, *args):
  1276.         return getint(self.tk.call((self._w, 'index') + args))
  1277.     def insert(self, *args):
  1278.         self.tk.call((self._w, 'insert') + args)
  1279.     def itemcget(self, tagOrId, option):
  1280.         return self.tk.call(
  1281.             (self._w, 'itemcget') + (tagOrId, '-'+option))
  1282.     def itemconfigure(self, tagOrId, cnf=None, **kw):
  1283.         if cnf is None and not kw:
  1284.             cnf = {}
  1285.             for x in self.tk.split(
  1286.                 self.tk.call(self._w,
  1287.                          'itemconfigure', tagOrId)):
  1288.                 cnf[x[0][1:]] = (x[0][1:],) + x[1:]
  1289.             return cnf
  1290.         if type(cnf) == StringType and not kw:
  1291.             x = self.tk.split(self.tk.call(
  1292.                 self._w, 'itemconfigure', tagOrId, '-'+cnf))
  1293.             return (x[0][1:],) + x[1:]
  1294.         self.tk.call((self._w, 'itemconfigure', tagOrId) +
  1295.                  self._options(cnf, kw))
  1296.     itemconfig = itemconfigure
  1297.     # lower, tkraise/lift hide Misc.lower, Misc.tkraise/lift,
  1298.     # so the preferred name for them is tag_lower, tag_raise
  1299.     # (similar to tag_bind, and similar to the Text widget);
  1300.     # unfortunately can't delete the old ones yet (maybe in 1.6)
  1301.     def tag_lower(self, *args):
  1302.         self.tk.call((self._w, 'lower') + args)
  1303.     lower = tag_lower
  1304.     def move(self, *args):
  1305.         self.tk.call((self._w, 'move') + args)
  1306.     def postscript(self, cnf={}, **kw):
  1307.         return self.tk.call((self._w, 'postscript') +
  1308.                     self._options(cnf, kw))
  1309.     def tag_raise(self, *args):
  1310.         self.tk.call((self._w, 'raise') + args)
  1311.     lift = tkraise = tag_raise
  1312.     def scale(self, *args):
  1313.         self.tk.call((self._w, 'scale') + args)
  1314.     def scan_mark(self, x, y):
  1315.         self.tk.call(self._w, 'scan', 'mark', x, y)
  1316.     def scan_dragto(self, x, y):
  1317.         self.tk.call(self._w, 'scan', 'dragto', x, y)
  1318.     def select_adjust(self, tagOrId, index):
  1319.         self.tk.call(self._w, 'select', 'adjust', tagOrId, index)
  1320.     def select_clear(self):
  1321.         self.tk.call(self._w, 'select', 'clear')
  1322.     def select_from(self, tagOrId, index):
  1323.         self.tk.call(self._w, 'select', 'from', tagOrId, index)
  1324.     def select_item(self):
  1325.         self.tk.call(self._w, 'select', 'item')
  1326.     def select_to(self, tagOrId, index):
  1327.         self.tk.call(self._w, 'select', 'to', tagOrId, index)
  1328.     def type(self, tagOrId):
  1329.         return self.tk.call(self._w, 'type', tagOrId) or None
  1330.     def xview(self, *args):
  1331.         if not args:
  1332.             return self._getdoubles(self.tk.call(self._w, 'xview'))
  1333.         self.tk.call((self._w, 'xview') + args)
  1334.     def xview_moveto(self, fraction):
  1335.         self.tk.call(self._w, 'xview', 'moveto', fraction)
  1336.     def xview_scroll(self, number, what):
  1337.         self.tk.call(self._w, 'xview', 'scroll', number, what)
  1338.     def yview(self, *args):
  1339.         if not args:
  1340.             return self._getdoubles(self.tk.call(self._w, 'yview'))
  1341.         self.tk.call((self._w, 'yview') + args)
  1342.     def yview_moveto(self, fraction):
  1343.         self.tk.call(self._w, 'yview', 'moveto', fraction)
  1344.     def yview_scroll(self, number, what):
  1345.         self.tk.call(self._w, 'yview', 'scroll', number, what)
  1346.  
  1347. class Checkbutton(Widget):
  1348.     def __init__(self, master=None, cnf={}, **kw):
  1349.         Widget.__init__(self, master, 'checkbutton', cnf, kw)
  1350.     def deselect(self):
  1351.         self.tk.call(self._w, 'deselect')
  1352.     def flash(self):
  1353.         self.tk.call(self._w, 'flash')
  1354.     def invoke(self):
  1355.         return self.tk.call(self._w, 'invoke')
  1356.     def select(self):
  1357.         self.tk.call(self._w, 'select')
  1358.     def toggle(self):
  1359.         self.tk.call(self._w, 'toggle')
  1360.  
  1361. class Entry(Widget):
  1362.     def __init__(self, master=None, cnf={}, **kw):
  1363.         Widget.__init__(self, master, 'entry', cnf, kw)
  1364.     def delete(self, first, last=None):
  1365.         self.tk.call(self._w, 'delete', first, last)
  1366.     def get(self):
  1367.         return self.tk.call(self._w, 'get')
  1368.     def icursor(self, index):
  1369.         self.tk.call(self._w, 'icursor', index)
  1370.     def index(self, index):
  1371.         return getint(self.tk.call(
  1372.             self._w, 'index', index))
  1373.     def insert(self, index, string):
  1374.         self.tk.call(self._w, 'insert', index, string)
  1375.     def scan_mark(self, x):
  1376.         self.tk.call(self._w, 'scan', 'mark', x)
  1377.     def scan_dragto(self, x):
  1378.         self.tk.call(self._w, 'scan', 'dragto', x)
  1379.     def selection_adjust(self, index):
  1380.         self.tk.call(self._w, 'selection', 'adjust', index)
  1381.     select_adjust = selection_adjust
  1382.     def selection_clear(self):
  1383.         self.tk.call(self._w, 'selection', 'clear')
  1384.     select_clear = selection_clear
  1385.     def selection_from(self, index):
  1386.         self.tk.call(self._w, 'selection', 'from', index)
  1387.     select_from = selection_from
  1388.     def selection_present(self):
  1389.         return self.tk.getboolean(
  1390.             self.tk.call(self._w, 'selection', 'present'))
  1391.     select_present = selection_present
  1392.     def selection_range(self, start, end):
  1393.         self.tk.call(self._w, 'selection', 'range', start, end)
  1394.     select_range = selection_range
  1395.     def selection_to(self, index):
  1396.         self.tk.call(self._w, 'selection', 'to', index)
  1397.     select_to = selection_to
  1398.     def xview(self, index):
  1399.         self.tk.call(self._w, 'xview', index)
  1400.     def xview_moveto(self, fraction):
  1401.         self.tk.call(self._w, 'xview', 'moveto', fraction)
  1402.     def xview_scroll(self, number, what):
  1403.         self.tk.call(self._w, 'xview', 'scroll', number, what)
  1404.  
  1405. class Frame(Widget):
  1406.     def __init__(self, master=None, cnf={}, **kw):
  1407.         cnf = _cnfmerge((cnf, kw))
  1408.         extra = ()
  1409.         if cnf.has_key('class_'):
  1410.             extra = ('-class', cnf['class_'])
  1411.             del cnf['class_']
  1412.         elif cnf.has_key('class'):
  1413.             extra = ('-class', cnf['class'])
  1414.             del cnf['class']
  1415.         Widget.__init__(self, master, 'frame', cnf, {}, extra)
  1416.  
  1417. class Label(Widget):
  1418.     def __init__(self, master=None, cnf={}, **kw):
  1419.         Widget.__init__(self, master, 'label', cnf, kw)
  1420.  
  1421. class Listbox(Widget):
  1422.     def __init__(self, master=None, cnf={}, **kw):
  1423.         Widget.__init__(self, master, 'listbox', cnf, kw)
  1424.     def activate(self, index):
  1425.         self.tk.call(self._w, 'activate', index)
  1426.     def bbox(self, *args):
  1427.         return self._getints(
  1428.             self.tk.call((self._w, 'bbox') + args)) or None
  1429.     def curselection(self):
  1430.         # XXX Ought to apply self._getints()...
  1431.         return self.tk.splitlist(self.tk.call(
  1432.             self._w, 'curselection'))
  1433.     def delete(self, first, last=None):
  1434.         self.tk.call(self._w, 'delete', first, last)
  1435.     def get(self, first, last=None):
  1436.         if last:
  1437.             return self.tk.splitlist(self.tk.call(
  1438.                 self._w, 'get', first, last))
  1439.         else:
  1440.             return self.tk.call(self._w, 'get', first)
  1441.     def index(self, index):
  1442.         i = self.tk.call(self._w, 'index', index)
  1443.         if i == 'none': return None
  1444.         return getint(i)
  1445.     def insert(self, index, *elements):
  1446.         self.tk.call((self._w, 'insert', index) + elements)
  1447.     def nearest(self, y):
  1448.         return getint(self.tk.call(
  1449.             self._w, 'nearest', y))
  1450.     def scan_mark(self, x, y):
  1451.         self.tk.call(self._w, 'scan', 'mark', x, y)
  1452.     def scan_dragto(self, x, y):
  1453.         self.tk.call(self._w, 'scan', 'dragto', x, y)
  1454.     def see(self, index):
  1455.         self.tk.call(self._w, 'see', index)
  1456.     def selection_anchor(self, index):
  1457.         self.tk.call(self._w, 'selection', 'anchor', index)
  1458.     select_anchor = selection_anchor
  1459.     def selection_clear(self, first, last=None):
  1460.         self.tk.call(self._w,
  1461.                  'selection', 'clear', first, last)
  1462.     select_clear = selection_clear
  1463.     def selection_includes(self, index):
  1464.         return self.tk.getboolean(self.tk.call(
  1465.             self._w, 'selection', 'includes', index))
  1466.     select_includes = selection_includes
  1467.     def selection_set(self, first, last=None):
  1468.         self.tk.call(self._w, 'selection', 'set', first, last)
  1469.     select_set = selection_set
  1470.     def size(self):
  1471.         return getint(self.tk.call(self._w, 'size'))
  1472.     def xview(self, *what):
  1473.         if not what:
  1474.             return self._getdoubles(self.tk.call(self._w, 'xview'))
  1475.         self.tk.call((self._w, 'xview') + what)
  1476.     def xview_moveto(self, fraction):
  1477.         self.tk.call(self._w, 'xview', 'moveto', fraction)
  1478.     def xview_scroll(self, number, what):
  1479.         self.tk.call(self._w, 'xview', 'scroll', number, what)
  1480.     def yview(self, *what):
  1481.         if not what:
  1482.             return self._getdoubles(self.tk.call(self._w, 'yview'))
  1483.         self.tk.call((self._w, 'yview') + what)
  1484.     def yview_moveto(self, fraction):
  1485.         self.tk.call(self._w, 'yview', 'moveto', fraction)
  1486.     def yview_scroll(self, number, what):
  1487.         self.tk.call(self._w, 'yview', 'scroll', number, what)
  1488.  
  1489. class Menu(Widget):
  1490.     def __init__(self, master=None, cnf={}, **kw):
  1491.         Widget.__init__(self, master, 'menu', cnf, kw)
  1492.     def tk_bindForTraversal(self):
  1493.         pass # obsolete since Tk 4.0
  1494.     def tk_mbPost(self):
  1495.         self.tk.call('tk_mbPost', self._w)
  1496.     def tk_mbUnpost(self):
  1497.         self.tk.call('tk_mbUnpost')
  1498.     def tk_traverseToMenu(self, char):
  1499.         self.tk.call('tk_traverseToMenu', self._w, char)
  1500.     def tk_traverseWithinMenu(self, char):
  1501.         self.tk.call('tk_traverseWithinMenu', self._w, char)
  1502.     def tk_getMenuButtons(self):
  1503.         return self.tk.call('tk_getMenuButtons', self._w)
  1504.     def tk_nextMenu(self, count):
  1505.         self.tk.call('tk_nextMenu', count)
  1506.     def tk_nextMenuEntry(self, count):
  1507.         self.tk.call('tk_nextMenuEntry', count)
  1508.     def tk_invokeMenu(self):
  1509.         self.tk.call('tk_invokeMenu', self._w)
  1510.     def tk_firstMenu(self):
  1511.         self.tk.call('tk_firstMenu', self._w)
  1512.     def tk_mbButtonDown(self):
  1513.         self.tk.call('tk_mbButtonDown', self._w)
  1514.     def tk_popup(self, x, y, entry=""):
  1515.         self.tk.call('tk_popup', self._w, x, y, entry)
  1516.     def activate(self, index):
  1517.         self.tk.call(self._w, 'activate', index)
  1518.     def add(self, itemType, cnf={}, **kw):
  1519.         self.tk.call((self._w, 'add', itemType) +
  1520.                  self._options(cnf, kw))
  1521.     def add_cascade(self, cnf={}, **kw):
  1522.         self.add('cascade', cnf or kw)
  1523.     def add_checkbutton(self, cnf={}, **kw):
  1524.         self.add('checkbutton', cnf or kw)
  1525.     def add_command(self, cnf={}, **kw):
  1526.         self.add('command', cnf or kw)
  1527.     def add_radiobutton(self, cnf={}, **kw):
  1528.         self.add('radiobutton', cnf or kw)
  1529.     def add_separator(self, cnf={}, **kw):
  1530.         self.add('separator', cnf or kw)
  1531.     def insert(self, index, itemType, cnf={}, **kw):
  1532.         self.tk.call((self._w, 'insert', index, itemType) +
  1533.                  self._options(cnf, kw))
  1534.     def insert_cascade(self, index, cnf={}, **kw):
  1535.         self.insert(index, 'cascade', cnf or kw)
  1536.     def insert_checkbutton(self, index, cnf={}, **kw):
  1537.         self.insert(index, 'checkbutton', cnf or kw)
  1538.     def insert_command(self, index, cnf={}, **kw):
  1539.         self.insert(index, 'command', cnf or kw)
  1540.     def insert_radiobutton(self, index, cnf={}, **kw):
  1541.         self.insert(index, 'radiobutton', cnf or kw)
  1542.     def insert_separator(self, index, cnf={}, **kw):
  1543.         self.insert(index, 'separator', cnf or kw)
  1544.     def delete(self, index1, index2=None):
  1545.         self.tk.call(self._w, 'delete', index1, index2)
  1546.     def entrycget(self, index, option):
  1547.         return self.tk.call(self._w, 'entrycget', index, '-' + option)
  1548.     def entryconfigure(self, index, cnf=None, **kw):
  1549.         if cnf is None and not kw:
  1550.             cnf = {}
  1551.             for x in self.tk.split(self.tk.call(
  1552.                 (self._w, 'entryconfigure', index))):
  1553.                 cnf[x[0][1:]] = (x[0][1:],) + x[1:]
  1554.             return cnf
  1555.         if type(cnf) == StringType and not kw:
  1556.             x = self.tk.split(self.tk.call(
  1557.                 (self._w, 'entryconfigure', index, '-'+cnf)))
  1558.             return (x[0][1:],) + x[1:]
  1559.         self.tk.call((self._w, 'entryconfigure', index)
  1560.               + self._options(cnf, kw))
  1561.     entryconfig = entryconfigure
  1562.     def index(self, index):
  1563.         i = self.tk.call(self._w, 'index', index)
  1564.         if i == 'none': return None
  1565.         return getint(i)
  1566.     def invoke(self, index):
  1567.         return self.tk.call(self._w, 'invoke', index)
  1568.     def post(self, x, y):
  1569.         self.tk.call(self._w, 'post', x, y)
  1570.     def type(self, index):
  1571.         return self.tk.call(self._w, 'type', index)
  1572.     def unpost(self):
  1573.         self.tk.call(self._w, 'unpost')
  1574.     def yposition(self, index):
  1575.         return getint(self.tk.call(
  1576.             self._w, 'yposition', index))
  1577.  
  1578. class Menubutton(Widget):
  1579.     def __init__(self, master=None, cnf={}, **kw):
  1580.         Widget.__init__(self, master, 'menubutton', cnf, kw)
  1581.  
  1582. class Message(Widget):
  1583.     def __init__(self, master=None, cnf={}, **kw):
  1584.         Widget.__init__(self, master, 'message', cnf, kw)
  1585.  
  1586. class Radiobutton(Widget):
  1587.     def __init__(self, master=None, cnf={}, **kw):
  1588.         Widget.__init__(self, master, 'radiobutton', cnf, kw)
  1589.     def deselect(self):
  1590.         self.tk.call(self._w, 'deselect')
  1591.     def flash(self):
  1592.         self.tk.call(self._w, 'flash')
  1593.     def invoke(self):
  1594.         return self.tk.call(self._w, 'invoke')
  1595.     def select(self):
  1596.         self.tk.call(self._w, 'select')
  1597.  
  1598. class Scale(Widget):
  1599.     def __init__(self, master=None, cnf={}, **kw):
  1600.         Widget.__init__(self, master, 'scale', cnf, kw)
  1601.     def get(self):
  1602.         value = self.tk.call(self._w, 'get')
  1603.         try:
  1604.             return getint(value)
  1605.         except ValueError:
  1606.             return getdouble(value)
  1607.     def set(self, value):
  1608.         self.tk.call(self._w, 'set', value)
  1609.     def coords(self, value=None):
  1610.         return self._getints(self.tk.call(self._w, 'coords', value))
  1611.     def identify(self, x, y):
  1612.         return self.tk.call(self._w, 'identify', x, y)
  1613.  
  1614. class Scrollbar(Widget):
  1615.     def __init__(self, master=None, cnf={}, **kw):
  1616.         Widget.__init__(self, master, 'scrollbar', cnf, kw)
  1617.     def activate(self, index):
  1618.         self.tk.call(self._w, 'activate', index)
  1619.     def delta(self, deltax, deltay):
  1620.         return getdouble(
  1621.             self.tk.call(self._w, 'delta', deltax, deltay))
  1622.     def fraction(self, x, y):
  1623.         return getdouble(self.tk.call(self._w, 'fraction', x, y))
  1624.     def identify(self, x, y):
  1625.         return self.tk.call(self._w, 'identify', x, y)
  1626.     def get(self):
  1627.         return self._getdoubles(self.tk.call(self._w, 'get'))
  1628.     def set(self, *args):
  1629.         self.tk.call((self._w, 'set') + args)
  1630.  
  1631. class Text(Widget):
  1632.     # XXX Add dump()
  1633.     def __init__(self, master=None, cnf={}, **kw):
  1634.         Widget.__init__(self, master, 'text', cnf, kw)
  1635.     def bbox(self, *args):
  1636.         return self._getints(
  1637.             self.tk.call((self._w, 'bbox') + args)) or None
  1638.     def tk_textSelectTo(self, index):
  1639.         self.tk.call('tk_textSelectTo', self._w, index)
  1640.     def tk_textBackspace(self):
  1641.         self.tk.call('tk_textBackspace', self._w)
  1642.     def tk_textIndexCloser(self, a, b, c):
  1643.         self.tk.call('tk_textIndexCloser', self._w, a, b, c)
  1644.     def tk_textResetAnchor(self, index):
  1645.         self.tk.call('tk_textResetAnchor', self._w, index)
  1646.     def compare(self, index1, op, index2):
  1647.         return self.tk.getboolean(self.tk.call(
  1648.             self._w, 'compare', index1, op, index2))
  1649.     def debug(self, boolean=None):
  1650.         return self.tk.getboolean(self.tk.call(
  1651.             self._w, 'debug', boolean))
  1652.     def delete(self, index1, index2=None):
  1653.         self.tk.call(self._w, 'delete', index1, index2)
  1654.     def dlineinfo(self, index):
  1655.         return self._getints(self.tk.call(self._w, 'dlineinfo', index))
  1656.     def get(self, index1, index2=None):
  1657.         return self.tk.call(self._w, 'get', index1, index2)
  1658.     # (Image commands are new in 8.0)
  1659.     def image_cget(self, index, option):
  1660.         if option[:1] != "-":
  1661.             option = "-" + option
  1662.         if option[-1:] == "_":
  1663.             option = option[:-1]
  1664.         return self.tk.call(self._w, "image", "cget", index, option)
  1665.     def image_configure(self, index, cnf={}, **kw):
  1666.         if not cnf and not kw:
  1667.             cnf = {}
  1668.             for x in self.tk.split(
  1669.                     self.tk.call(
  1670.                     self._w, "image", "configure", index)):
  1671.                 cnf[x[0][1:]] = (x[0][1:],) + x[1:]
  1672.             return cnf
  1673.         apply(self.tk.call,
  1674.               (self._w, "image", "configure", index)
  1675.               + self._options(cnf, kw))
  1676.     def image_create(self, index, cnf={}, **kw):
  1677.         return apply(self.tk.call,
  1678.                  (self._w, "image", "create", index)
  1679.                  + self._options(cnf, kw))
  1680.     def image_names(self):
  1681.         return self.tk.call(self._w, "image", "names")
  1682.     def index(self, index):
  1683.         return self.tk.call(self._w, 'index', index)
  1684.     def insert(self, index, chars, *args):
  1685.         self.tk.call((self._w, 'insert', index, chars) + args)
  1686.     def mark_gravity(self, markName, direction=None):
  1687.         return self.tk.call(
  1688.             (self._w, 'mark', 'gravity', markName, direction))
  1689.     def mark_names(self):
  1690.         return self.tk.splitlist(self.tk.call(
  1691.             self._w, 'mark', 'names'))
  1692.     def mark_set(self, markName, index):
  1693.         self.tk.call(self._w, 'mark', 'set', markName, index)
  1694.     def mark_unset(self, *markNames):
  1695.         self.tk.call((self._w, 'mark', 'unset') + markNames)
  1696.     def scan_mark(self, x, y):
  1697.         self.tk.call(self._w, 'scan', 'mark', x, y)
  1698.     def scan_dragto(self, x, y):
  1699.         self.tk.call(self._w, 'scan', 'dragto', x, y)
  1700.     def search(self, pattern, index, stopindex=None,
  1701.            forwards=None, backwards=None, exact=None,
  1702.            regexp=None, nocase=None, count=None):
  1703.         args = [self._w, 'search']
  1704.         if forwards: args.append('-forwards')
  1705.         if backwards: args.append('-backwards')
  1706.         if exact: args.append('-exact')
  1707.         if regexp: args.append('-regexp')
  1708.         if nocase: args.append('-nocase')
  1709.         if count: args.append('-count'); args.append(count)
  1710.         if pattern[0] == '-': args.append('--')
  1711.         args.append(pattern)
  1712.         args.append(index)
  1713.         if stopindex: args.append(stopindex)
  1714.         return self.tk.call(tuple(args))
  1715.     def see(self, index):
  1716.         self.tk.call(self._w, 'see', index)
  1717.     def tag_add(self, tagName, index1, index2=None):
  1718.         self.tk.call(
  1719.             self._w, 'tag', 'add', tagName, index1, index2)
  1720.     def tag_unbind(self, tagName, sequence, funcid=None):
  1721.         self.tk.call(self._w, 'tag', 'bind', tagName, sequence, '')
  1722.         if funcid:
  1723.             self.deletecommand(funcid)
  1724.     def tag_bind(self, tagName, sequence, func, add=None):
  1725.         return self._bind((self._w, 'tag', 'bind', tagName),
  1726.                   sequence, func, add)
  1727.     def tag_cget(self, tagName, option):
  1728.         if option[:1] != '-':
  1729.             option = '-' + option
  1730.         if option[-1:] == '_':
  1731.             option = option[:-1]
  1732.         return self.tk.call(self._w, 'tag', 'cget', tagName, option)
  1733.     def tag_configure(self, tagName, cnf={}, **kw):
  1734.         if type(cnf) == StringType:
  1735.             x = self.tk.split(self.tk.call(
  1736.                 self._w, 'tag', 'configure', tagName, '-'+cnf))
  1737.             return (x[0][1:],) + x[1:]
  1738.         self.tk.call(
  1739.               (self._w, 'tag', 'configure', tagName)
  1740.               + self._options(cnf, kw))
  1741.     tag_config = tag_configure
  1742.     def tag_delete(self, *tagNames):
  1743.         self.tk.call((self._w, 'tag', 'delete') + tagNames)
  1744.     def tag_lower(self, tagName, belowThis=None):
  1745.         self.tk.call(self._w, 'tag', 'lower', tagName, belowThis)
  1746.     def tag_names(self, index=None):
  1747.         return self.tk.splitlist(
  1748.             self.tk.call(self._w, 'tag', 'names', index))
  1749.     def tag_nextrange(self, tagName, index1, index2=None):
  1750.         return self.tk.splitlist(self.tk.call(
  1751.             self._w, 'tag', 'nextrange', tagName, index1, index2))
  1752.     def tag_prevrange(self, tagName, index1, index2=None):
  1753.         return self.tk.splitlist(self.tk.call(
  1754.             self._w, 'tag', 'prevrange', tagName, index1, index2))
  1755.     def tag_raise(self, tagName, aboveThis=None):
  1756.         self.tk.call(
  1757.             self._w, 'tag', 'raise', tagName, aboveThis)
  1758.     def tag_ranges(self, tagName):
  1759.         return self.tk.splitlist(self.tk.call(
  1760.             self._w, 'tag', 'ranges', tagName))
  1761.     def tag_remove(self, tagName, index1, index2=None):
  1762.         self.tk.call(
  1763.             self._w, 'tag', 'remove', tagName, index1, index2)
  1764.     def window_cget(self, index, option):
  1765.         if option[:1] != '-':
  1766.             option = '-' + option
  1767.         if option[-1:] == '_':
  1768.             option = option[:-1]
  1769.         return self.tk.call(self._w, 'window', 'cget', index, option)
  1770.     def window_configure(self, index, cnf={}, **kw):
  1771.         if type(cnf) == StringType:
  1772.             x = self.tk.split(self.tk.call(
  1773.                 self._w, 'window', 'configure',
  1774.                 index, '-'+cnf))
  1775.             return (x[0][1:],) + x[1:]
  1776.         self.tk.call(
  1777.               (self._w, 'window', 'configure', index)
  1778.               + self._options(cnf, kw))
  1779.     window_config = window_configure
  1780.     def window_create(self, index, cnf={}, **kw):
  1781.         self.tk.call(
  1782.               (self._w, 'window', 'create', index)
  1783.               + self._options(cnf, kw))
  1784.     def window_names(self):
  1785.         return self.tk.splitlist(
  1786.             self.tk.call(self._w, 'window', 'names'))
  1787.     def xview(self, *what):
  1788.         if not what:
  1789.             return self._getdoubles(self.tk.call(self._w, 'xview'))
  1790.         self.tk.call((self._w, 'xview') + what)
  1791.     def yview(self, *what):
  1792.         if not what:
  1793.             return self._getdoubles(self.tk.call(self._w, 'yview'))
  1794.         self.tk.call((self._w, 'yview') + what)
  1795.     def yview_pickplace(self, *what):
  1796.         self.tk.call((self._w, 'yview', '-pickplace') + what)
  1797.  
  1798. class _setit:
  1799.     def __init__(self, var, value):
  1800.         self.__value = value
  1801.         self.__var = var
  1802.     def __call__(self, *args):
  1803.         self.__var.set(self.__value)
  1804.  
  1805. class OptionMenu(Menubutton):
  1806.     def __init__(self, master, variable, value, *values):
  1807.         kw = {"borderwidth": 2, "textvariable": variable,
  1808.               "indicatoron": 1, "relief": RAISED, "anchor": "c",
  1809.               "highlightthickness": 2}
  1810.         Widget.__init__(self, master, "menubutton", kw)
  1811.         self.widgetName = 'tk_optionMenu'
  1812.         menu = self.__menu = Menu(self, name="menu", tearoff=0)
  1813.         self.menuname = menu._w
  1814.         menu.add_command(label=value, command=_setit(variable, value))
  1815.         for v in values:
  1816.             menu.add_command(label=v, command=_setit(variable, v))
  1817.         self["menu"] = menu
  1818.  
  1819.     def __getitem__(self, name):
  1820.         if name == 'menu':
  1821.             return self.__menu
  1822.         return Widget.__getitem__(self, name)
  1823.  
  1824.     def destroy(self):
  1825.         Menubutton.destroy(self)
  1826.         self.__menu = None
  1827.  
  1828. class Image:
  1829.     def __init__(self, imgtype, name=None, cnf={}, master=None, **kw):
  1830.         self.name = None
  1831.         if not master:
  1832.             master = _default_root
  1833.             if not master:
  1834.                 raise RuntimeError, 'Too early to create image'
  1835.         self.tk = master.tk
  1836.         if not name:
  1837.             name = `id(self)`
  1838.             # The following is needed for systems where id(x)
  1839.             # can return a negative number, such as Linux/m68k:
  1840.             if name[0] == '-': name = '_' + name[1:]
  1841.         if kw and cnf: cnf = _cnfmerge((cnf, kw))
  1842.         elif kw: cnf = kw
  1843.         options = ()
  1844.         for k, v in cnf.items():
  1845.             if callable(v):
  1846.                 v = self._register(v)
  1847.             options = options + ('-'+k, v)
  1848.         self.tk.call(('image', 'create', imgtype, name,) + options)
  1849.         self.name = name
  1850.     def __str__(self): return self.name
  1851.     def __del__(self):
  1852.         if self.name:
  1853.             try:
  1854.                 self.tk.call('image', 'delete', self.name)
  1855.             except TclError:
  1856.                 # May happen if the root was destroyed
  1857.                 pass
  1858.     def __setitem__(self, key, value):
  1859.         self.tk.call(self.name, 'configure', '-'+key, value)
  1860.     def __getitem__(self, key):
  1861.         return self.tk.call(self.name, 'configure', '-'+key)
  1862.     def configure(self, **kw):
  1863.         res = ()
  1864.         for k, v in _cnfmerge(kw).items():
  1865.             if v is not None:
  1866.                 if k[-1] == '_': k = k[:-1]
  1867.                 if callable(v):
  1868.                     v = self._register(v)
  1869.                 res = res + ('-'+k, v)
  1870.         self.tk.call((self.name, 'config') + res)
  1871.     config = configure
  1872.     def height(self):
  1873.         return getint(
  1874.             self.tk.call('image', 'height', self.name))
  1875.     def type(self):
  1876.         return self.tk.call('image', 'type', self.name)
  1877.     def width(self):
  1878.         return getint(
  1879.             self.tk.call('image', 'width', self.name))
  1880.  
  1881. class PhotoImage(Image):
  1882.     def __init__(self, name=None, cnf={}, master=None, **kw):
  1883.         apply(Image.__init__, (self, 'photo', name, cnf, master), kw)
  1884.     def blank(self):
  1885.         self.tk.call(self.name, 'blank')
  1886.     def cget(self, option):
  1887.         return self.tk.call(self.name, 'cget', '-' + option)
  1888.     # XXX config
  1889.     def __getitem__(self, key):
  1890.         return self.tk.call(self.name, 'cget', '-' + key)
  1891.     # XXX copy -from, -to, ...?
  1892.     def copy(self):
  1893.         destImage = PhotoImage()
  1894.         self.tk.call(destImage, 'copy', self.name)
  1895.         return destImage
  1896.     def zoom(self,x,y=''):
  1897.         destImage = PhotoImage()
  1898.         if y=='': y=x
  1899.         self.tk.call(destImage, 'copy', self.name, '-zoom',x,y)
  1900.         return destImage
  1901.     def subsample(self,x,y=''):
  1902.         destImage = PhotoImage()
  1903.         if y=='': y=x
  1904.         self.tk.call(destImage, 'copy', self.name, '-subsample',x,y)
  1905.         return destImage
  1906.     def get(self, x, y):
  1907.         return self.tk.call(self.name, 'get', x, y)
  1908.     def put(self, data, to=None):
  1909.         args = (self.name, 'put', data)
  1910.         if to:
  1911.             if to[0] == '-to':
  1912.                 to = to[1:]
  1913.             args = args + ('-to',) + tuple(to)
  1914.         self.tk.call(args)
  1915.     # XXX read
  1916.     def write(self, filename, format=None, from_coords=None):
  1917.         args = (self.name, 'write', filename)
  1918.         if format:
  1919.             args = args + ('-format', format)
  1920.         if from_coords:
  1921.             args = args + ('-from',) + tuple(from_coords)
  1922.         self.tk.call(args)
  1923.  
  1924. class BitmapImage(Image):
  1925.     def __init__(self, name=None, cnf={}, master=None, **kw):
  1926.         apply(Image.__init__, (self, 'bitmap', name, cnf, master), kw)
  1927.  
  1928. def image_names(): return _default_root.tk.call('image', 'names')
  1929. def image_types(): return _default_root.tk.call('image', 'types')
  1930.  
  1931. ######################################################################
  1932. # Extensions:
  1933.  
  1934. class Studbutton(Button):
  1935.     def __init__(self, master=None, cnf={}, **kw):
  1936.         Widget.__init__(self, master, 'studbutton', cnf, kw)
  1937.         self.bind('<Any-Enter>',       self.tkButtonEnter)
  1938.         self.bind('<Any-Leave>',       self.tkButtonLeave)
  1939.         self.bind('<1>',               self.tkButtonDown)
  1940.         self.bind('<ButtonRelease-1>', self.tkButtonUp)
  1941.  
  1942. class Tributton(Button):
  1943.     def __init__(self, master=None, cnf={}, **kw):
  1944.         Widget.__init__(self, master, 'tributton', cnf, kw)
  1945.         self.bind('<Any-Enter>',       self.tkButtonEnter)
  1946.         self.bind('<Any-Leave>',       self.tkButtonLeave)
  1947.         self.bind('<1>',               self.tkButtonDown)
  1948.         self.bind('<ButtonRelease-1>', self.tkButtonUp)
  1949.         self['fg']               = self['bg']
  1950.         self['activebackground'] = self['bg']
  1951.  
  1952. ######################################################################
  1953. # Test:
  1954.  
  1955. def _test():
  1956.     root = Tk()
  1957.     label = Label(root, text="Proof-of-existence test for Tk")
  1958.     label.pack()
  1959.     test = Button(root, text="Click me!",
  1960.               command=lambda root=root: root.test.configure(
  1961.                   text="[%s]" % root.test['text']))
  1962.     test.pack()
  1963.     root.test = test
  1964.     quit = Button(root, text="QUIT", command=root.destroy)
  1965.     quit.pack()
  1966.     # The following three commands are needed so the window pops
  1967.     # up on top on Windows...
  1968.     root.iconify()
  1969.     root.update()
  1970.     root.deiconify()
  1971.     root.mainloop()
  1972.  
  1973. if __name__ == '__main__':
  1974.     _test()
  1975.